package com.briup.cms.service.impl;

import com.briup.cms.bean.Comment;
import com.briup.cms.dao.CommentDao;
import com.briup.cms.exception.ServiceException;
import com.briup.cms.service.CommentService;
import com.briup.cms.util.ResultCode;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    CommentDao commentDao;

    @Override
    public Page<Comment> findAll(Integer pageNum, Integer pageSize) throws ServiceException {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return commentDao.findAll(pageRequest);
    }

    @Override
    public void saveOrUpdateComment(Comment comment) throws ServiceException {
        commentDao.save(comment);
    }

    @Override
    public void deleteCommentInBatch(List<Long> ids) throws ServiceException {
        for (Long id:ids){
           deleteCommentById(id);
        }
    }

    @Override
    public void deleteCommentById(Long id) throws ServiceException {
        Comment comment = findCommentById(id);
        if (comment==null){
            throw new ServiceException(ResultCode.Comment_NOT_EXIST);
        }
        commentDao.deleteById(id);
    }

    @Override
    public Page<Comment> findAllByArticleId(Long articleId, Integer pageNum, Integer pageSize) throws ServiceException {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return commentDao.findByArticleId(articleId,pageRequest);
    }

    @Override
    public Comment findCommentById(Long id) throws ServiceException {
        return commentDao.findById(id).orElse(null);
    }


}
